const shopcar = JSON.parse(localStorage['car'] || '[]')

export default {
  state: {
    shopcar
  },
  mutations: {
    addToCar(state, goods) {
      if(!goods) return
      
      let isHave = false
      state.shopcar.some(item => {
        if(item.id === goods.id){
          item.count += parseInt(goods.count)
          isHave = true
          return true
        }
      });
      if(!isHave) state.shopcar.push(goods)

      localStorage['car'] = JSON.stringify(state.shopcar)
    },
    updateSelected(state, {id, sel}) {
      state.shopcar.some(item => {
        if(item.id === id) {
          item.selected = sel
          return true
        }
      })

      localStorage['car'] = JSON.stringify(state.shopcar)
    },
    updateGoodsCount(state, {id, count}) {
      state.shopcar.some(item => {
        if(item.id === id) {
          item.count = count
          return true
        }
      })

      localStorage['car'] = JSON.stringify(state.shopcar)
    },
    delGoodsInfo(state, id) {
      state.shopcar.some((item,i) => {
        if(item.id === id) {
          state.shopcar.splice(i,1)
          return true
        }
      })

      localStorage['car'] = JSON.stringify(state.shopcar)
    }
  },
  getters: {
    getCountTotal(state) {
      let total = 0
      state.shopcar.forEach(item => {
        total += parseInt(item.count)
      });
      return total
    },
    getIdStr(state) {
      const ids = []
      let idsStr = ''
      state.shopcar.forEach(item => {
        ids.push(item.id)
      })
      if(ids.length <= 0) return 
      idsStr = ids.join(',')
      return idsStr
    },
    getGoodsSelected(state, id) {
      const obj = {}
      state.shopcar.forEach(item => {
        obj[item.id] = item.selected
      })
      return obj
    },
    countAndId(state) {
      const map = new Map()
      state.shopcar.forEach(item => {
        map.set(item.id, item.count)
      })
      return map
    },
    countAndAmount(state) {
      const obj = {
        count: 0,
        amount: 0
      }
      state.shopcar.forEach(item => {
        if(item.selected) {
          obj.count += parseInt(item.count)
          obj.amount += item.price * parseInt(item.count)
        }
      })
      return obj
    }
  }
}